package com.lintesis.lintesisview.common;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.hibernate.Session;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.api.Checkbox;
import org.zkoss.zul.api.Div;
import org.zkoss.zul.api.Label;
import org.zkoss.zul.api.Textbox;

import com.lintesis.lintesismodel.common.hibernate.ConnectionManager;
import com.lintesis.lintesismodel.common.hibernate.GenericDAO;
import com.lintesis.lintesismodel.users.User;
import com.lintesis.lintesisview.common.menu.UserWorkspace;

public class LoginCtrl extends GenericForwardComposer
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -1474911143054608615L;
	Textbox usertb;
	Textbox pwdtb;
	Checkbox chkRememberPassword;
	Div loginDiv;
	Div userDiv;
	Label msg;
	Label userName;

	public void onClick$loginBtn() throws InterruptedException
	{
		try
		{
			doLogin();
		} catch (Exception e)
		{
			Messagebox.show(e.toString());
			e.printStackTrace();
		}
	}

	public void onOK$pwdtb(Event event) throws Exception
	{
		doLogin();
	}
	void doLogin() throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
			InstantiationException
	{
		if (usertb.getValue().equals("") || pwdtb.getValue().equals(""))
		{
			msg.setValue("Debe ingresar nombre de usuario y password.");
			return;
		}

		User user = new User();
		user.setLogin(usertb.getValue());
		

		Session ss = ConnectionManager.getSession();
		ss.clear();
		List<User> list = new GenericDAO<User>(ss).getByBussinessObject(user, 0, 0);

		if (list.size() == 0)
		{
			msg.setValue("Nombre de Usuario o Contraseña incorrecta.");
			return;
		}

		user = list.get(0);
	
		if (user.getEnabled() == null || !user.getEnabled())
		{
			msg.setValue("Usuario no habilitado.");
			return;
		}
		if (!user.getPassword().equals(pwdtb.getValue()))
		{
			msg.setValue("Nombre de Usuario o Contraseña incorrecta.");
			return;
		}
	
		session.setAttribute("user", user);
		
		UserWorkspace userWorkspace = new UserWorkspace();

		userWorkspace.getGrantedAuthoritySet().addAll(user.getUsrRights());

//		for(Role r : user.getRols()){
//			for(UsrRight ri:r.getUsrRights()){
//				System.out.println("derecho "+ri.getName());
//			}
//			
//		}
		session.setAttribute("userWorkspace", userWorkspace);

		userWorkspace.setSession(Sessions.getCurrent());

		userWorkspace.sethSession(ss);
		userWorkspace.afterCreationTasks();
		storePassword(user);
		Executions.sendRedirect("workspace.zul");

	}
	CookieController cookieController=new CookieController();
	public  void storePassword(User user)
	{
		
		if(chkRememberPassword.isChecked())
		{
			cookieController.setCookie("lintesis.userName", user.getLogin(),999999999);
			cookieController.setCookie("lintesis.userPassword", user.getPassword(),999999999);
			cookieController.setCookie("lintesis.rememberPassord", ""+chkRememberPassword.isChecked(),999999999);
		}
		else
		{
			cookieController.setCookie("lintesis.userName", null,999999999);
			cookieController.setCookie("lintesis.userPassword", null,999999999);
			cookieController.setCookie("lintesis.rememberPassord", null,999999999);			
		}
	}
	
	public void restorePassword()
	{
		String userName=cookieController.getCookie("lintesis.userName");
		String password=cookieController.getCookie("lintesis.userPassword");
		String rememberPassword=cookieController.getCookie("lintesis.rememberPassord");
		if (userName!=null)
			usertb.setValue(userName);
		if(password!=null)
			pwdtb.setValue(password);
		if(rememberPassword!=null)
			chkRememberPassword.setChecked(Boolean.valueOf(rememberPassword));
	}
	
	  @Override
	  public void doAfterCompose(Component comp) throws Exception {
	    super.doAfterCompose(comp);
	    restorePassword();
	  }

}
